package com.wang.mandkey.tool;

import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.imageio.ImageIO;

import com.sun.xml.internal.messaging.saaj.util.ByteOutputStream;
import com.wang.mandkey.utils.ProjectEnvironment;

/**
 * 
 * @author wang 下午04:13:08-2011 TODO 工具类
 */
public class Tool {

	/**
	 * 获取pc机的高度和宽度
	 * 
	 * @return
	 */
	public static Dimension getScreenDimen() {
		Dimension dimen = Toolkit.getDefaultToolkit().getScreenSize();
		return dimen;
	}

	public static Pattern p = Pattern
			.compile("((\\d{1,2}|1\\d\\d|2[0-4]\\d|25[0-5])\\.(\\d{1,2}|1\\d\\d|2[0-4]\\d|25[0-5])\\.(\\d{1,2}|1\\d\\d|2[0-4]\\d|25[0-5])\\.(\\d{1,2}|1\\d\\d|2[0-4]\\d|25[0-5]))");

	/**
	 * 获取本机局域网ip
	 * 
	 * @return
	 */
	public static String[] getLocalIp() {
		Enumeration<NetworkInterface> netInterfaces = null;
		ArrayList<String> iplist = new ArrayList<String>();
		try {
			netInterfaces = NetworkInterface.getNetworkInterfaces();
			while (netInterfaces.hasMoreElements()) {
				NetworkInterface ni = netInterfaces.nextElement();
				Enumeration<InetAddress> ips = ni.getInetAddresses();
				while (ips.hasMoreElements()) {
					String ip = ips.nextElement().getHostAddress();
					Matcher matcher = p.matcher(ip);
					if (!ip.equals("127.0.0.1") && matcher.matches())
						iplist.add(ip);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		String ips[]=new String[iplist.size()];
		for(int i=0;i<ips.length;i++){
			ips[i]=iplist.get(i);
		}
		return ips;
	}

	/**
	 * 生成屏幕截图
	 */
	public static void createScreenShort(String FileName) {
		Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
		Rectangle rect = new Rectangle(0, 0, d.width, d.height);
		BufferedImage image = ScriptRunner.robot.createScreenCapture(rect);
		try {
			File path = new File(ProjectEnvironment.STRING_FRAME_PATH);
			if (!path.isDirectory() || path.exists() == true) {
				path.mkdir();
			}
			ImageIO.write(image, "jpg", new File(FileName));
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	/**
	 * 对图片生成缩略图
	 * 
	 * @param srcPath
	 *            图片地址
	 * @param descPath
	 *            生成之后放入的地方
	 * @param newWidth
	 *            新图片的宽度
	 * @return 缩略图的地址
	 * @throws IOException
	 */
	public static InputStream scaleImage(String srcPath, String descPath,
			int newWidth) {
		InputStream inputStream = null;
		File srcFile = new File(srcPath);
		File descFile = new File(descPath);
		try {
			if (!srcFile.exists()) {
				throw new FileNotFoundException(srcPath);
			} else {

				AffineTransform transform = new AffineTransform();
				BufferedImage bis = ImageIO.read(srcFile);

				int w = bis.getWidth();
				int h = bis.getHeight();

				int nw = newWidth;
				int nh = (nw * h) / w;

				if (nh > newWidth) {
					nh = newWidth;
					nw = (nh * w) / h;
				}

				double sx = (double) nw / w;
				double sy = (double) nh / h;

				transform.setToScale(sx, sy);
				AffineTransformOp ato = new AffineTransformOp(transform, null);
				BufferedImage bid = new BufferedImage(nw, nh,
						BufferedImage.TYPE_3BYTE_BGR);
				ato.filter(bis, bid);
				ImageIO.write(bid, "jpeg", descFile);

				// ByteInputStream bin;
				// ByteOutputStream bout = null;
				// bout.newInputStream();
				// 上面3行是优化方案

			}

			if (descFile.isFile() && descFile.exists() == true) {
				inputStream = new FileInputStream(descFile);
			}

		} catch (Exception e) {
			e.printStackTrace();
			System.err.println("My god its get wrong:" + e.getMessage());
		}
		return inputStream;
	}

	/**
	 * 获取当前截图
	 * 
	 * @return
	 */
	public static InputStream getNowScreen() {
		InputStream inputStream = null;
		String fname = ProjectEnvironment.STRING_FRAME_PATH + File.separator
				+ "now.jpg";
		createScreenShort(fname);// 生成截图
		inputStream = scaleImage(fname, ProjectEnvironment.STRING_FRAME_PATH
				+ File.separator + "now2.jpg",
				ProjectEnvironment.INT_SCREEN_WIDTH_SCALE);
		return inputStream;
	}

	/**
	 * 获取当前截图
	 * 
	 * @return
	 */
	public static byte[] getNowScreen2() {
		byte data[]=null;
		try {
			ByteOutputStream byo = new ByteOutputStream();
			Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
			Rectangle rect = new Rectangle(0, 0, d.width, d.height);
			BufferedImage image = ScriptRunner.robot.createScreenCapture(rect);
			byo.flush();
			byo.reset();
			ImageIO.write(image, "png", byo);
			
			data=byo.getBytes();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return data;
	}

	/**
	 * 获取带缩略图的截屏，参数是缩略后的宽度
	 * 
	 * @param nw
	 * @return
	 */
	public static InputStream getNowScreenScale(int nws) {
		InputStream inputStream = null;
		try {
			ByteOutputStream byo = new ByteOutputStream();
			Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
			Rectangle rect = new Rectangle(0, 0, d.width, d.height);
			BufferedImage image = ScriptRunner.robot.createScreenCapture(rect);
			byo.flush();
			byo.reset();

			ImageIO.write(image, "jpg", byo);
			inputStream = byo.newInputStream();

			AffineTransform transform = new AffineTransform();
			BufferedImage bis = ImageIO.read(inputStream); // 链接屏幕的缓存

			int w = bis.getWidth();
			int h = bis.getHeight();

			int nw = nws;
			int nh = (nw * h) / w;

			if (nh > nws) {
				nh = nws;
				nw = (nh * w) / h;
			}

			double sx = (double) nw / w;
			double sy = (double) nh / h;
			transform.setToScale(sx, sy);
			AffineTransformOp ato = new AffineTransformOp(transform, null);
			BufferedImage bid = new BufferedImage(nw, nh,
					BufferedImage.TYPE_3BYTE_BGR);
			ato.filter(bis, bid);
			ByteOutputStream byotemp = new ByteOutputStream();
			ImageIO.write(bid, "png", byotemp);
			return byotemp.newInputStream();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 线程休眠
	 * 
	 * @param times
	 *            void 下午04:46:51 2011
	 */
	public static void sleep(long times) {

		try {
			Thread.sleep(times);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	// public static void main(String[] args) {
	//
	// long s=System.currentTimeMillis();
	// InputStream is = getNowScreen();
	// if(is==null){
	// System.out.println("over bad");
	// }else{
	// System.out.println("over ok");
	// }
	// long e=System.currentTimeMillis();
	// System.out.println("toast:"+(e-s));
	// }
	
	public static int[] parserPhoneDimen(String phoneInfo){
		String content=phoneInfo.substring(phoneInfo.indexOf("(")+1, phoneInfo.lastIndexOf(")"));
		String[] strdata = content.split(",");
		int dimen[]=new int[2];
		dimen[0]=Integer.parseInt(strdata[0]);
		dimen[1]=Integer.parseInt(strdata[1]);
		return dimen;
	}
}
